﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Linq;
using System.Xml;
using Aulac.Global.Enums;
using Aulac.Global.Data;
using Aulac.Global.Common;
using Aulac.Global.Xml;
using Aulac.Rsc.Ems;
using Aulac.Rsc.Ems.Tags;
using Aulac.Client.Data.Helper;
using Aulac.Verb.Ems;
using Aulac.Global.AccessRight;
using Aulac.Rsc;
using Aulac.Client.Global.Interface;
using Aulac.Client.Ems.WinForm.Store.DataFiles;
namespace Aulac.Client.Ems.WinForm.Stores
{
    partial class FormRelsMdnStore
    {
        private ObjectTypes mObjTypeID = ObjectTypes.CBYT;
        private bool mIsCheckInstock = true;
        //private string mVchName = "";
        #region Override Methods
        public override void OnFormLoad()
        {
            try
            {
                base.OnFormLoad();
                InitGrd();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }
        protected override bool OnShowDetailVoucher()
        {
            if (ValueHelper.isEmpty(mVoucherID))
                return false;

            XmlDataDocument xmlDoc = DataMngStoreHelper.GetVchRelsStore(mVoucherID, mVchType);
            XmlElement eHeader = XmlProcess.GetVchHeaderElm(xmlDoc);
            XmlNodeList listNode = XmlProcess.GetListVchLineItem(xmlDoc);
            foreach (Aulac.Client.Global.Interface.IAulacValueDataCtrl ctr in GetListControlsOnForm())
                try
                {
                    if (!(ctr is Aulac.Client.Controls.Ems.ComboBo.ComboObjByTypeCtrl))
                        ctr.SetValueToControl(eHeader);
                }
                catch
                { }
            ObjectTypes oType = (ObjectTypes)ValueHelper.ChangeType(XmlProcess.GetValueAtrb(eHeader, tagVch.Inv.PartTypeID), typeof(ObjectTypes));
            if (oType == ObjectTypes.None)
            {
                oType = mObjTypeID;
                cboObjStoreRec.ComboObjectTyeps.ClearDataContainer();
            }
            cboObjStoreRec.ComboObjectTyeps.ObjTypeID = oType;
            string sObjPrkID = XmlProcess.GetValueAtrb(eHeader, tagVch.Inv.PartPrkID);
            if (!ValueHelper.isEmpty(sObjPrkID))
                cboObjStoreRec.ObjPrkID = sObjPrkID;

            grdLine.AddDataToControl(listNode);
            for (int i = 1; i < grdLine.grdData.Rows.Count; i++)
                grdLine.grdData.SetValueCell(i, grdLine.ColumnsGrd.PriceInExc, grdLine.grdData.GetValueDataCell(i, tagVch.Inv.PriceInExc));
            mVchName = XmlProcess.GetValueAtrb(eHeader, tagVch.Inv.VchName);
            grdLine.SetTotalSummary();
            return true;

            //base.OnShowDetailVoucher();
            //return GetVchOutStore(mVoucherID, mVchType);
        }
      
        protected override void OnAddNewVoucher()
        {
            this.grdLine.ClearValueTtAmt();
            txtNo.Text = GetNewVchNo(ref mVchName);
            if (cboObjStoreRec.ComboObjectTyeps.IsEmptyDataInList)
                cboObjStoreRec.ComboObjectTyeps.ReLoadDataToControl();

            if (cboStoreRels.IsEmptyDataInList)
                cboStoreRels.ReLoadDataToControl();
            if (!cboStoreRels.IsEmptyDataInList)
                cboStoreRels.ComBoboxData.SelectedIndex = 0;
            if (cboPsnRels.IsEmptyDataInList)
                cboPsnRels.ReLoadDataToControl();
            if (!cboPsnRels.IsEmptyDataInList)
                cboPsnRels.ComBoboxData.SelectedIndex = 0;
            if (cboPsnInStock.IsEmptyDataInList)
                cboPsnInStock.ReLoadDataToControl();
            if (!cboPsnInStock.IsEmptyDataInList)
                cboPsnInStock.ComBoboxData.SelectedIndex = 0;
            cbTagStoreType.TagStoreTypeID = TagStoreTypes.OutputToPntInDept;
            this.Text = mVchName;
            cboStoreRels.Focus();
        }
        protected override void OnEditVoucher()
        {
            base.OnEditVoucher();
            mIsCheckInstock = true;
            if (cboObjStoreRec.ComboObjectTyeps.IsEmptyDataInList)
                cboObjStoreRec.ComboObjectTyeps.ReLoadDataToControl();
            cboStoreRels.Focus();
        }
        protected override bool OnBeginSaveVoucher()
        {
            //grdLine.grdData.RemoveAllRowsByColEmpty(tagItems.Item.ItemGrpID, tagItems.Item.ItemID);
            if (cbTagStoreType.IsEmptyValue)
            {
                Aulac.UtilityTools.AulacMsg.Show(Aulac.Client.Ems.WinForm.Stores.Lang.AulacLangMsg.GetMsg(Aulac.Client.Ems.WinForm.Stores.Lang.AulacCodes.ErrAlEmsCMS001));
                cbTagStoreType.Focus();
                return false;
            }            
            if (grdLine.grdData.Rows.Count <= 2)
            {
                Aulac.UtilityTools.AulacMsg.Show(Aulac.Client.Ems.WinForm.Stores.Lang.AulacLangMsg.GetMsg(Aulac.Client.Ems.WinForm.Stores.Lang.AulacCodes.ErrAlEmsCMS003));
                grdLine.Focus();
                return false;
            }
            int iCount = grdLine.ReadOnly == true ? grdLine.grdData.Rows.Count : grdLine.grdData.Rows.Count - 1;
            for (int i = 1; i < iCount; i++)
            {
                int mQuantity = (int)ValueHelper.ChangeType(grdLine.grdData.GetValueDataCell(i, grdLine.ColumnsGrd.Quantity), typeof(int));
                string sItemID = (string)ValueHelper.ChangeType(grdLine.grdData.GetValueDataCell(i, grdLine.ColumnsGrd.ItemID), typeof(string));
                if (mQuantity == 0)
                {
                    if (mQuantity == 0)
                        Aulac.UtilityTools.MsgBox.Show(string.Format("Số lượng dòng [ {0} ] không được bằng không !", i), Aulac.UtilityTools.MsgBox.Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    else
                        Aulac.UtilityTools.MsgBox.Show(string.Format("Mã y tế ở dòng [ {0} ] đang rỗng !", i), Aulac.UtilityTools.MsgBox.Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    grdLine.grdData.SelectedIndexGridRow = i;
                    return false;
                }
            }
            return true;
        }
        protected override bool OnSaveVoucherData(ref XmlDataDocument xmlData)
        {
            try
            {
                return SaveRelsMdnStore(FormMode, ref xmlData);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message, ex);
            }
        }
        protected override bool OnDeleteDataVoucher()
        {
            /* Update code: 02/17/2011 by Thangnc */
            try
            {
                XmlDataDocument xmlDoc = CreateXmlDocument(AulacEmsVerb.MngStore.RelsStore.DelVchRelsStore, AulacEmsVerb.MngStore.RelsStore.Noun.RelsStore);
                XmlProcess.AddValueParamItem(xmlDoc, tagVch.Inv.VchRelsInvPrkID, mVoucherID);
                XmlProcess.AddValueParamItem(xmlDoc, tagVch.Inv.VchTypeID, mVchType);
                XmlProcess.AddValueParamItem(xmlDoc, tagVch.Inv.IsCheckQtyLost, mIsCheckInstock);

                ProcessRequest(xmlDoc);
                return true;
            }
            catch (Exception ex)
            {
                Aulac.Global.Exceptions.AulacException x = new Aulac.Global.Exceptions.AulacException(ex);
                if (ErrCodes.ErrorCode.Error0010.Equals(x.ErrorCode))
                {
                    XmlNodeList lst = XmlProcess.GetListVchLineItem(x.XmlEcexption);
                    foreach (XmlElement eLine in lst)
                    {
                        DataRow row = grdLine.AulacDataGrid.GetFirstDataRowByKey(tagVch.Inv.ItemPrkID, XmlProcess.GetValueAtrb(eLine, tagVch.Inv.ItemPrkID));
                        DataTableProcess.SetValueDataRow(row, tagVch.Inv.OverInstock, true);
                    }
                    return false;
                }
                else throw ex;

            }
        }
        protected override void OnSetStateControls(FormModes pFormMode)
        {
            base.OnSetStateControls(pFormMode);
            bool isReadOnly = false;
            if (pFormMode == FormModes.NewMode || pFormMode == FormModes.EditMode)
                isReadOnly = false;
            else
                isReadOnly = true;
            foreach (Aulac.Client.Global.Interface.IAulacStateCtrl ctr in GetListControlsOnForm())
            {
                ctr.FormMode = pFormMode;
                ctr.Enabled = !isReadOnly;
                ctr.ReadOnly = isReadOnly;
            }
            grdLine.FormMode = pFormMode;
        }
        protected override void OnClearValueControls()
        {
            base.OnClearValueControls();
            foreach (Aulac.Client.Global.Interface.IAulacValueDataCtrl ctr in GetListControlsOnForm())
                ctr.ClearValueControls();
            grdLine.ClearDataContainer();
            grdLine.ClearValueTtAmt();
        }
        protected override void OnSetAccessRight(AccessRights accRight)
        {
            base.OnSetAccessRight(accRight);
            if (!accRight.IsAdministrator)
                txtNo.Enabled = false;
            else
                txtNo.Enabled = true;
        }
        protected override void OnRefreshList()
        {
            XmlDataDocument xmlDoc = CreateXmlDocument(AulacEmsVerb.MngStore.RelsStore.GetListVchRelsStore, AulacEmsVerb.MngStore.RelsStore.Noun.RelsStore);
            XmlProcess.AddValueParamItem(xmlDoc, tagVch.Inv.VchDateFrom, dtVchFromDate.ShortDate);
            XmlProcess.AddValueParamItem(xmlDoc, tagVch.Inv.VchDateTo, dtVchToDate.ShortDate);
            grdInfo.ClearDataContainer();

            DataHelper.GetDataFromServerToControl(grdInfo, xmlDoc);
        }
        protected override void OnPrintVoucher()
        {
            Aulac.Client.Reports.Ems.VchPrints.RptVchPrint.ShowReport(GetValueToXml(), DataFileInfos.FolderFileRpt, DataFileInfos.VchRelsStoreName);
        }
        #endregion

        #region Private Methods
        private void Init()
        {
            mVchType = VchTypes.VchRelsMdnStore;
            mVchName = Aulac.Client.Data.Ems.Helper.VchHelper.GetVchNameOnServer(mVchType);
            this.Text = mVchName;
            FieldVchPrkID = tagVch.Inv.VchRelsInvPrkID;
            grdInfo.DataSource = new Aulac.Client.Data.Ems.DataSet.StoreMngs.ViewVchRelsInvDataTable();
            grdLine.ShowHideColumn(false, grdLine.ColumnsGrd.ItemGrpID);
            grdLine.ListMdnGrpTypes = new List<ItemGrpTypes>() { ItemGrpTypes.GrpDrug, ItemGrpTypes.GrpEquMdn, ItemGrpTypes.GrpFlood, ItemGrpTypes.GrpMdnMaterials, ItemGrpTypes.GrpTradMdn };

            cbTagStoreType.SetParamTagStoreTypes(
                        TagStoreTypes.OuputOther,
                        TagStoreTypes.OuputRepair,
                        TagStoreTypes.OutputExpCommon,
                        TagStoreTypes.OutputExpCurePnt,
                        TagStoreTypes.OutputOverdue,
                        TagStoreTypes.OutputToPnt,
                        TagStoreTypes.OutputToPntInClinic,
                        TagStoreTypes.OutputToPntInDept);

            cboPsnInStock.ArrPsnTypeID = new List<PsnTypes> { PsnTypes.Instock, PsnTypes.Accounting, PsnTypes.Clinical };
            cboPsnRels.ArrPsnTypeID = new List<PsnTypes> { PsnTypes.Clinical, PsnTypes.Doctor, PsnTypes.HspOrderly, PsnTypes.Instock, PsnTypes.Nurse, PsnTypes.Manager };
            cboObjStoreRec.SetCollectionsObjTypes(ObjectTypes.BN, ObjectTypes.KHOAPHONG, ObjectTypes.NCC, ObjectTypes.OBJNKPKCB, ObjectTypes.TRAMYTE);
            cboStoreRels.LstStoreTypes = new List<StoreTypes> { StoreTypes.Buseniss, StoreTypes.Clinic, StoreTypes.DeptDrug, StoreTypes.Manager, StoreTypes.Other, StoreTypes.Pnt, StoreTypes.Program };
        }
        private void InitGrd()
        {
            grdInfo.ClearColumsShow();
            grdInfo.AddColumnShow(new Aulac.UtilityTools.ColumnGridViewInfo() { ColCaption = "Số CT", ColName = tagVch.Inv.VchNo, DisplayIndex = 0 });
            grdInfo.AddColumnShow(new Aulac.UtilityTools.ColumnGridViewInfo() { ColCaption = "Ngày CT", ColName = tagVch.Inv.VchDate, DisplayIndex = 1 });
            grdInfo.AddColumnShow(new Aulac.UtilityTools.ColumnGridViewInfo() { ColCaption = "Kí hiệu", ColName = tagVch.Inv.VchSign, DisplayIndex = 2 });
            grdInfo.AddColumnShow(new Aulac.UtilityTools.ColumnGridViewInfo() { ColCaption = "Số VAT", ColName = tagVch.Inv.VchTaxNo, DisplayIndex = 3 });
            grdInfo.AddColumnShow(new Aulac.UtilityTools.ColumnGridViewInfo() { ColCaption = "Ngày VAT", ColName = tagVch.Inv.VchTaxDate, DisplayIndex = 4 });
            grdInfo.AddColumnShow(new Aulac.UtilityTools.ColumnGridViewInfo() { ColCaption = "Kho xuất", ColName = tagVch.Inv.StoreRelsName, DisplayIndex = 5 });
            grdInfo.AddColumnShow(new Aulac.UtilityTools.ColumnGridViewInfo() { ColCaption = "Người giao", ColName = tagVch.Inv.RelsPsnName, DisplayIndex = 6 });
            grdInfo.AddColumnShow(new Aulac.UtilityTools.ColumnGridViewInfo() { ColCaption = "Quản lý kho", ColName = tagVch.Inv.PsnInStockName, DisplayIndex = 7 });
            grdInfo.AddColumnShow(new Aulac.UtilityTools.ColumnGridViewInfo() { ColCaption = "Nguồn xuất", ColName = tagVch.Inv.TagStoreTypeName, DisplayIndex = 8 });
            grdInfo.AddColumnShow(new Aulac.UtilityTools.ColumnGridViewInfo() { ColCaption = "Thuế", ColName = tagVch.Inv.TaxRate, DisplayIndex = 9 });
            grdInfo.AddColumnShow(new Aulac.UtilityTools.ColumnGridViewInfo() { ColCaption = "Nơi nhận", ColName = tagVch.Inv.PartName, DisplayIndex = 10 });
            grdInfo.AddColumnShow(new Aulac.UtilityTools.ColumnGridViewInfo() { ColCaption = "Người nhận", ColName = tagVch.Inv.RecvPsnName, DisplayIndex = 11 });
            grdInfo.AddColumnShow(new Aulac.UtilityTools.ColumnGridViewInfo() { ColCaption = "Diễn giải", ColName = tagVch.Inv.Note, DisplayIndex = 12 });
            grdInfo.AddColumnShow(new Aulac.UtilityTools.ColumnGridViewInfo() { ColCaption = "Tổng tiền", ColName = tagVch.Inv.AmtSumInExc, DisplayIndex = 13 });
        }
        private void SetFieldMember()
        {
            txtNo.FieldMember = tagVch.Inv.VchNo;
            txtNote.FieldMember = tagVch.Inv.Note;
            txtTaxNo.FieldMember = tagVch.Inv.VchTaxNo;
            txtSign.FieldMember = tagVch.Inv.VchSign;
            txtTaxRateH.FieldMember = tagVch.Inv.TaxRate;
            dtTaxDate.FieldMember = tagVch.Inv.VchTaxDate;
            dtVchDate.FieldMember = tagVch.Inv.VchDate;
            
            // Thu kho
            cboPsnInStock.RemoveFieldMappingAll();
            cboPsnInStock.AddFieldMapping(tagItems.Psn.PsnPrkID, tagVch.Inv.PsnInStockPrkID);
            cboPsnInStock.AddFieldMapping(tagItems.Psn.PsnName, tagVch.Inv.PsnInStockName);
            
            // Nguoi nhan
            txtPsnRec.FieldMember = tagVch.Inv.RecvPsnName;
            //cboPsnRec.AddFieldMapping(tagItems.Psn.PsnPrkID, tagItems.Store.RelsPerson);

            // Nguoi giao
            cboPsnRels.AddFieldMapping(tagItems.Psn.PsnPrkID, tagVch.Inv.RelsPsnPrkID);
            cboPsnRels.AddFieldMapping(tagItems.Psn.PsnName, tagVch.Inv.RelsPsnName);

            // Kho nhan
            //cboStoreRec.AddFieldMapping(tagItems.Store.StorePrkID, tagVch.Inv.StoreRecPrkID);
            //cboStoreRec.AddFieldMapping(tagItems.Store.StoreName, tagVch.Inv.StoreRecName);

            // Kho xuat
            cboStoreRels.AddFieldMapping(tagItems.Store.StorePrkID, tagVch.Inv.StorePrkID);
            cboStoreRels.AddFieldMapping(tagItems.Store.StoreName, tagVch.Inv.StoreRelsName);

            // Loai nguon xuat
            cbTagStoreType.AddFieldMapping(tagItems.Store.TagStoreTypeID, tagVch.Inv.TagStoreTypeID);
        }
        private void ShowDetialData(XmlDataDocument xmlDoc)
        {
            XmlElement eHeader = XmlProcess.GetVchHeaderElm(xmlDoc);

            foreach (Control ctr in GetListControlsOnForm())
                if (ctr is Aulac.Client.Global.Interface.IAulacValueDataCtrl)
                    ((Aulac.Client.Global.Interface.IAulacValueDataCtrl)ctr).SetValueToControl(eHeader);

            cbTagStoreType.SetValueToControl(eHeader);

            XmlNodeList nodeList = XmlProcess.GetListVchLineItem(xmlDoc);
            grdLine.AddDataToControl(nodeList);
        }
        private void SetAmtTotal()
        {
            //txtTtlAmtLine.Double = grdLine.grdData.SumColum(this.grdLine.ColumnsGrd.AmtLineInExc);
            //txtTtlTax.Double = grdLine.grdData.SumColum(this.grdLine.ColumnsGrd.AmtTaxLineInExc);
        }
        private List<IAulacDataControl> GetListControlsOnForm()
        {
            List<IAulacDataControl> mListControl = null;
            GetListAulacDataControls(ref mListControl, grpParner);
            GetListAulacDataControls(ref mListControl, grpVch);
            GetListAulacDataControls(ref mListControl, pnl);
            return mListControl;
        }
        private XmlDataDocument GetValueToXml()
        {
            XmlDataDocument xmlDoc = CreateXmlDocument("", "");
            if (this.TaskWorking == TaskWorks.Priting)
            {
                XmlElement eHeader = XmlProcess.AddVchHeaderElm(ref xmlDoc);
                XmlProcess.SetAtrb(ref eHeader, tagVch.Inv.RecvPsnName, txtPsnRec.Text);
                XmlProcess.SetAtrb(ref eHeader, tagVch.Inv.PsnInStockName, cboPsnInStock.PsnName);
                XmlProcess.SetAtrb(ref eHeader, tagVch.Inv.VchNo, txtNo.Text);
                XmlProcess.SetAtrb(ref eHeader, tagVch.Inv.VchDate, dtVchDate.Text);
                XmlProcess.SetAtrb(ref eHeader, tagItems.Store.StoreName, cboStoreRels.StoreName);

                XmlElement eVLines = XmlProcess.AddVchLinesElm(ref xmlDoc);                
                ((IAulacDataContainerCtrl)grdLine).GetDataToChildNodeXml(eVLines);
            }
            return xmlDoc;
        }
        #endregion
    }
}
